<template>
  <div class="header">Media Files</div>
  <a-spin :spinning="loading" :delay="1000" tip="downloading" size="large">
    <div class="media-panel-wrapper">
      <a-table class="media-table" :columns="columns" :data-source="mediaData.data" row-key="fingerprint"
        :pagination="paginationProp" :scroll="{ x: '100%', y: 600 }" @change="refreshData">
        <template v-for="col in ['name', 'path']" #[col]="{ text,record }" :key="col">
          <a-tooltip :title="text">
              <a v-if="col === 'name'" @click="viewMedia(record)">{{ text }}</a>
              <span v-else>{{ text }}</span>
          </a-tooltip>
        </template>
        <template #original="{ text }">
          {{ text }}
        </template>
        <template #action="{ record }">
          <a-tooltip title="download">
            <a class="fz18" @click="downloadMedia(record)"><DownloadOutlined /></a>
          </a-tooltip>

          <a-tooltip title="view">
            <a class="fz18" @click="viewMedia(record)" style ="margin-left:10px;"><EyeOutlined /></a>
          </a-tooltip>

          <!-- <a-tooltip title="download">
            <a class="fz18" @click="downloadCutMedia(record)"  style ="margin-left:10px;"><DownloadOutlined /></a>
          </a-tooltip> -->

        </template>
      </a-table>
    </div>
    </a-spin>
    <a-image :width="200"
      :style="{ display: 'none' }" :preview="{
        visible: mediaVisible,
        onVisibleChange: setVisible,
      }" :src="mediaSrc" ></a-image>

      <!-- <div v-if="mediaInfoOpen" style="position:absolute;zIndex:10000;width:180px;height:240px;background-color:#0172e8;">
        {mediaInfoStr}
      </div> -->
  <a-modal
      :forceRender="true"
      v-model:visible="videoModalOpen"
      :title="videoMediaName"
      width="80%"
      :footer="null"
    >
      视频内容
      <video style="width:100%;min-height:200px" id="mediaVideo"
      src=''
       autoplay controls>
      </video>
    </a-modal>

</template>

<script setup lang="ts">
import { ref } from '@vue/reactivity'
import { TableState } from 'ant-design-vue/lib/table/interface'
import { onMounted, reactive } from 'vue'
import { IPage } from '../api/http/type'
import { ELocalStorageKey } from '../types/enums'
import { downloadFile } from '../utils/common'
import { downloadMediaFile, getMediaFilePath, getMediaFiles, downloadCutMediaFile, getMediaInfo } from '/@/api/media'
import { DownloadOutlined, EyeOutlined } from '@ant-design/icons-vue'
import { message, Pagination } from 'ant-design-vue'
import { load } from '@amap/amap-jsapi-loader'
import axios, { CancelTokenSource } from 'axios'

const workspaceId = localStorage.getItem(ELocalStorageKey.WorkspaceId)!
const loading = ref(false)

const videoModalOpen = ref<boolean>(false)
const mediaInfoOpen = ref<boolean>(true)

const mediaInfoStr = ref<String>('')

const videoMediaName = ref<String>('')
const mediaSrc = ref<String>('')
const mediaVisible = ref<boolean>(false)
const setVisible = (value:any): void => {
  mediaVisible.value = value
  if (!value) {
    currentMedia = null
    mediaSrc.value = ''
    // 隐藏div
    if (customDiv != null) {
      document.body.removeChild(customDiv)
    }
    customDiv = null
    document.removeEventListener('mousemove', mouseMoveHandler)
    document.removeEventListener('mouseup', mouseUpHandler)
  }
}

let currentMedia:any = null
let cancelTokenSource: CancelTokenSource | undefined
let isDragging = false
let offsetX = 0
let offsetY = 0
let customDiv:any = null
const mouseDownHandler = (event:any) => {
  isDragging = true
  offsetX = event.clientX - customDiv.offsetLeft
  offsetY = event.clientY - customDiv.offsetTop
}

const mouseMoveHandler = (event:any) => {
  if (isDragging) {
    const x = event.clientX - offsetX
    const y = event.clientY - offsetY
    customDiv.style.left = `${x}px`
    customDiv.style.top = `${y}px`
  }
}
const mouseUpHandler = () => {
  isDragging = false
}
const handleOk = (e: MouseEvent) => {
  // console.log(e)
  videoModalOpen.value = false
}

const columns = [
  {
    title: 'File Name',
    dataIndex: 'file_name',
    ellipsis: true,
    slots: { customRender: 'name' }
  },
  {
    title: 'File Path',
    dataIndex: 'file_path',
    ellipsis: true,
    slots: { customRender: 'path' }
  },
  // {
  //   title: 'FileSize',
  //   dataIndex: 'size',
  // },
  {
    title: 'Drone',
    dataIndex: 'drone'
  },
  {
    title: 'Payload Type',
    dataIndex: 'payload'
  },
  {
    title: 'Original',
    dataIndex: 'is_original',
    slots: { customRender: 'original' }
  },
  {
    title: 'Created',
    dataIndex: 'create_time'
  },
  {
    title: 'Action',
    slots: { customRender: 'action' }
  }
]
const body: IPage = {
  page: 1,
  total: 0,
  page_size: 50
}
const paginationProp = reactive({
  pageSizeOptions: ['20', '50', '100'],
  showQuickJumper: true,
  showSizeChanger: true,
  pageSize: 50,
  current: 1,
  total: 0
})

type Pagination = TableState['pagination']

interface MediaFile {
  fingerprint: string,
  drone: string,
  payload: string,
  is_original: string,
  file_name: string,
  file_path: string,
  create_time: string,
  file_id: string,
}

const mediaData = reactive({
  data: [] as MediaFile[]
})

onMounted(() => {
  getFiles()
})

function getFiles () {
  getMediaFiles(workspaceId, body).then(res => {
    mediaData.data = res.data.list
    paginationProp.total = res.data.pagination.total
    paginationProp.current = res.data.pagination.page
    // console.info(mediaData.data[0])
  })
}

function refreshData (page: Pagination) {
  body.page = page?.current!
  body.page_size = page?.pageSize!
  getFiles()
}

function handleRecognitionClick (recoginizeType:string = 'flower') {
  if (currentMedia == null) {
    alert('图片加载错误，请关闭重试')
  }
  // loading.value = true
  let liContent = '加载中...'
  let boxContent = '<h1 style="color:#fff">智能识别</h1><div style="padding:10px;color:#fff;"><h3 style="color:#fff;">识别结果：</h3><div">' + liContent + '</div><div>'

  if (customDiv === undefined || customDiv === null) {
    customDiv = document.createElement('div')
    customDiv.id = 'mediaInfoShowId'

    customDiv.innerHTML = boxContent
    document.body.appendChild(customDiv)

    customDiv.addEventListener('mousedown', mouseDownHandler)
    document.addEventListener('mousemove', mouseMoveHandler)
    document.addEventListener('mouseup', mouseUpHandler)
  } else {
    customDiv.innerHTML = boxContent
  }

  if (cancelTokenSource) {
    cancelTokenSource.cancel('取消之前的识别请求')
  }
  cancelTokenSource = axios.CancelToken.source()
  try {
    getMediaInfo(workspaceId, currentMedia.file_id, cancelTokenSource.token, recoginizeType).then(res => {
      if (!res) {
        return
      }
      mediaInfoOpen.value = true

      liContent = ''
      if (recoginizeType === 'flower') {
        if (res.data.result !== undefined) {
          res.data.result.forEach((va:any) => {
            liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">' + va.name + '</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + va.score * 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + va.score + '</span></div>'
          })
        } else {
          liContent = '没有识别结果'
        }
      } else if (recoginizeType === 'car') {
        if (res.data.vehicle_num !== undefined) {
          liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">car</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + res.data.vehicle_num.car + '</span></div>'
          liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">bus</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + res.data.vehicle_num.bus + '</span></div>'
          liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">carplate</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + res.data.vehicle_num.carplate + '</span></div>'
          liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">motorbike</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + res.data.vehicle_num.motorbike + '</span></div>'
          liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">tricycle</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + res.data.vehicle_num.tricycle + '</span></div>'
          liContent += '<div style="width:100%;margin-top:6px;"><span style="display:inline-block;width:30%;">truck</span><span style="display:inline-block;width:40%;padding:0px 10px;"><span style="display:inline-block;width:' + 100 + '%;height:2px;background-color:#fff;"></span></span><span style="display:inline-block;width:30%;">' + res.data.vehicle_num.truck + '</span></div>'
          mediaSrc.value = res.data.vehicle_result_img_path
        } else {
          liContent = '没有识别结果'
        }
      } else {
        liContent = '没有识别结果'
      }

      boxContent = '<h1 style="color:#fff">智能识别</h1><div style="padding:10px;color:#fff;"><h3 style="color:#fff;">识别结果：</h3><div">' + liContent + '</div><div>'
      customDiv.innerHTML = boxContent
    }).finally(() => {
    // loading.value = false
    })
  } catch (e) {

  }
}

function addRecognitionBtn () {
  // 增加按钮
  setTimeout(function () {
    const parentDom = document.getElementsByClassName('ant-image-preview-root')[0].getElementsByClassName('ant-image-preview-operations')[0]
    // console.log('parentDom', parentDom)

    const newLi = document.createElement('li')

    const newSpanCar = document.createElement('span')
    newSpanCar.title = '智能识别车辆'
    newSpanCar.className = 'anticon anticon-rotate-left ant-image-preview-operations-icon'
    newSpanCar.innerHTML = '<svg t="1716563991125" style="width:24px;height:24px;cursor:pointer;margin-right:20px" class="icon" viewBox="0 0 1028 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1500" width="32" height="32"><path fill="#ffffff" d="M984.224299 203.663551h40.47352V0H821.53271v40.47352h162.691589zM40.872274 819.738318H0.398754V1023.401869h203.165109v-40.573209H40.872274zM984.523364 820.834891v162.691589H821.333333v40.47352h203.663552V820.834891zM1.894081 0.598131h-0.498442v203.165109H41.869159V41.071651h163.190031V0.598131H1.894081z" p-id="1501"></path><path d="M865.395639 432.747664h-66.591901c-3.190031 0-6.080997 0.897196-8.672897 2.392523l-30.00623-90.417446c-9.570093-51.439252-45.757009-76.161994-90.218069-76.161993H388.087227c-51.040498 0-82.043614 33.29595-90.218068 76.161993l-30.105919 90.716511c-2.691589-1.595016-5.88162-2.5919-9.17134-2.5919h-66.5919c-10.267913 0-18.542056 8.274143-18.542056 18.542056v16.049844c0 10.267913 8.274143 18.542056 18.542056 18.542056l25.221184 4.286605c-7.975078 15.551402-12.461059 33.29595-12.461059 54.031152l-9.370717 106.666667c0 3.090343 0.199377 6.280374 0.598131 9.370717-0.398754 1.894081-0.598131 3.987539-0.598131 5.981308v128.299065c0 18.242991 14.853583 33.096573 33.096573 33.096574h50.442368c18.242991 0 33.096573-14.753894 33.096573-33.096574v-41.271028h434.043614v41.271028c0 18.242991 14.853583 33.096573 33.096573 33.096574h50.342679c18.242991 0 33.096573-14.753894 33.096573-33.096574V666.417445c0-2.093458-0.299065-4.087227-0.59813-5.981308 0.398754-3.190031 0.598131-6.280374 0.59813-9.370716l-9.370716-106.666667c0-20.735202-4.58567-38.579439-12.560748-54.130841l24.623053-4.186916c10.267913 0 18.542056-8.274143 18.542056-18.542056v-16.049844c0.099688-10.367601-8.174455-18.741433-18.442367-18.741433z m-545.295951-18.94081l22.031153-58.616823 0.299066-1.395638c2.193146-11.862928 7.077882-13.956386 14.35514-23.127726h344.922118c7.277259 9.370717 11.862928 11.76324 13.856698 23.028037l22.429906 60.11215 8.174455 32.697819c-1.894081 23.925234-30.604361 42.766355-54.529595 42.766355H366.35514c-23.925234 0-52.635514-18.841121-54.529595-42.766355l8.274143-32.697819z m15.451714 278.82866c-27.713396 0-50.043614-22.429907-50.043614-50.043614 0-27.713396 22.429907-50.043614 50.043614-50.043613 27.713396 0 50.043614 22.429907 50.043614 50.043613s-22.429907 50.043614-50.043614 50.043614z m386.890966 0c-27.713396 0-50.143302-22.429907-50.143303-50.043614 0-27.713396 22.429907-50.043614 50.143303-50.043613 27.713396 0 50.043614 22.429907 50.043613 50.043613s-22.330218 50.043614-50.043613 50.043614z" p-id="1502" fill="#ffffff"></path></svg>'
    newSpanCar.addEventListener('click', function () {
      handleRecognitionClick('car')
    })
    newLi.appendChild(newSpanCar)
    const newSpan = document.createElement('span')
    newSpan.title = '智能识别'
    newSpan.className = 'anticon anticon-rotate-left ant-image-preview-operations-icon'
    newSpan.innerHTML = '<svg style="width:24px;height:24px;cursor:pointer;" t="1715045297934" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4980" width="32" height="32"><path d="M111.542857 662.820571c22.162286 0 40.155429 17.993143 40.155429 40.155429v145.334857c0 1.755429 1.536 3.364571 3.584 3.364572h126.902857a39.789714 39.789714 0 1 1 0 79.506285H155.282286a83.382857 83.382857 0 0 1-83.821715-82.870857V702.902857c0-22.162286 17.993143-40.155429 40.082286-40.155428z m800.914286 0c22.089143 0 40.082286 17.993143 40.082286 40.155429v145.334857a83.382857 83.382857 0 0 1-83.821715 82.870857h-126.902857a39.789714 39.789714 0 0 1 0-79.506285h126.902857c2.048 0 3.657143-1.609143 3.657143-3.364572V702.902857c0-22.162286 17.92-40.155429 40.082286-40.155428zM486.546286 363.739429l139.702857 333.604571H542.354286l-32.914286-77.019429H381.220571l-32.914285 77.019429h-84.114286l139.776-333.531429h82.578286z m248.173714 0v333.604571H662.674286v-333.531429h71.972571zM445.44 444.269714l-48.128 116.516572H493.714286L445.44 444.269714z m423.204571-330.166857a83.382857 83.382857 0 0 1 83.821715 82.944v145.334857a40.082286 40.082286 0 0 1-80.237715 0V197.046857c0-1.828571-1.536-3.364571-3.584-3.364571h-126.902857a39.789714 39.789714 0 1 1 0-79.579429h126.902857z m-565.613714 9.728a39.789714 39.789714 0 1 1 0 79.579429H155.282286c-2.048 0-3.657143 1.536-3.657143 3.364571v124.708572a40.082286 40.082286 0 1 1-80.164572 0V206.774857a83.382857 83.382857 0 0 1 83.821715-82.944h147.748571z" p-id="4981" fill="#ffffff"></path></svg>'
    newSpan.addEventListener('click', function () {
      handleRecognitionClick('flower')
    })
    newLi.appendChild(newSpan)

    parentDom.appendChild(newLi)
  }, 1000)
}

function viewMedia (media: MediaFile) {
  const fileName = media.file_name
  videoMediaName.value = fileName
  let isVideo = false

  if (fileName.endsWith('.MP4')) {
    isVideo = true
  }
  loading.value = true
  getMediaFilePath(workspaceId, media.file_id).then(res => {
    if (!res) {
      return
    }
    if (!isVideo) {
      mediaSrc.value = res.data
      setVisible(true)

      // 延迟增加按钮
      currentMedia = media
      addRecognitionBtn()
    } else {
      showMediaVideo(res.data)
    }
  }).finally(() => {
    loading.value = false
  })
}

function showMediaVideo (mediaPath:string) {
  document.getElementById('mediaVideo')?.setAttribute('src', mediaPath)
  videoModalOpen.value = true
}

function downloadMedia (media: MediaFile) {
  loading.value = true
  downloadMediaFile(workspaceId, media.file_id).then(res => {
    if (!res) {
      return
    }
    const data = new Blob([res])
    downloadFile(data, media.file_name)
  }).finally(() => {
    loading.value = false
  })
}

function downloadCutMedia (media: MediaFile) {
  loading.value = true
  downloadCutMediaFile(workspaceId, media.file_id).then(res => {
    if (!res) {
      return
    }
    const data = new Blob([res])
    downloadFile(data, media.file_name)
  }).finally(() => {
    loading.value = false
  })
}

</script>

<style lang="scss" scoped>
.media-panel-wrapper {
  width: 100%;
  padding: 16px;
  .media-table {
    background: #fff;
    margin-top: 10px;
  }
  .action-area {
    color: $primary;
    cursor: pointer;
  }
}
.header {
  width: 100%;
  height: 60px;
  background: #fff;
  padding: 16px;
  font-size: 20px;
  font-weight: bold;
  text-align: start;
  color: #000;
}

</style>
